<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card shadow="always" header="工单统计情况">
          <el-table :data="orderstatisticsData" style="width: 100%" height="40%" v-loading="orderstatisticsLoading">
            <el-table-column fixed prop="month" label="月份" width="80" align="center" />
            <el-table-column fixed prop="county" label="区县" width="120" align="center" />
            <el-table-column prop="orderNum" label="工单总数" width="100" align="center" sortable />
            <el-table-column prop="exitOrderNum" label="退服工单总数" width="140" align="center" sortable />
            <el-table-column prop="notCloseOrderNum" label="未闭环工单数" width="140" align="center" sortable />
            <el-table-column prop="orderTimeoutNum" label="超时工单数" width="140" align="center" sortable />
            <el-table-column prop="alarmTimeoutNum" label="超时故障数" width="140" align="center" sortable />
            <el-table-column prop="markOrderNum" label="采编工单总数" min-width="140" align="center" sortable />
            <template #empty>
              <el-empty :image-size="40" />
            </template>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="always">
          <template #header>
            <div class="card-header">
              <span style="margin-right: 50px;">工单维护指标</span>
              <el-button type="primary" icon="Download" @click="orderMaintenanceExportData" :disabled="true"
                title="正在开发中">导出</el-button>
              <!-- <el-button type="primary" icon="Download" @click="testApi">测试</el-button> -->
            </div>
          </template>
          <el-table :data="orderMaintenanceData" style="width: 100%" height="40%" v-loading="orderMaintenanceLoading">
            <el-table-column fixed prop="month" label="月份" width="80" align="center" />
            <el-table-column fixed prop="county" label="区县" width="120" align="center" />
            <el-table-column prop="unavailableDuration" label="不可用时长" width="120" align="center" />
            <!-- 汇总的 原本假的占50%+分公司真实的也站50%公式算出来 -->
            <el-table-column prop="orderQuality" label="故障工单质量" width="140" align="center" sortable />
            <!-- 假的50% -->
            <el-table-column prop="eomsQuality" label="工单质量" width="180" align="center" />
            <!-- 真的50% -->
            <el-table-column prop="faultQuality" label="故障质量" width="180" align="center" />
            <!-- <el-table-column prop="longTimeOrderNum" label="超长告警" width="120" align="center" sortable>
              <template #default="scope">
                <a v-if='scope.row.county == "合计"' @click="downloadLongTimeOrder"
                  style="color: blue;text-decoration-line:underline">{{
                    scope.row.longTimeOrderNum }}</a>
              </template>
            </el-table-column> -->
            <!-- <el-table-column prop="overFrequencyOrderNum" label="超频告警" width="120" align="center" sortable>
              <template #default="scope">
                <a v-if='scope.row.county == "合计"' href="#" style="color: blue;text-decoration-line:underline">{{
                  scope.row.overFrequencyOrderNum }}</a>
              </template>
            </el-table-column> -->
            <!-- <el-table-column prop="zeroFlowSiteNum" label="零流量" align="center" /> -->
            <template #empty>
              <el-empty :image-size="40" />
            </template>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-card shadow="always" header="工单详情" style="margin-top: 20px;">
          <el-form :model="queryParams" :inline="true" label-width="120px">
            <el-form-item label="归属区县：" prop="county">
              <!-- <el-input v-model="queryParams.county" placeholder="请输入所属区县" clearable style="width: 200px" /> -->
              <el-select v-model="queryParams.county" placeholder="请选择所属区县" style="width: 240px" clearable>
                <el-option v-for="item in countyOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="小区名称：" prop="neName">
              <el-input v-model="queryParams.neName" placeholder="请输入小区名称" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item label="工单编号：" prop="orderId">
              <el-input v-model="queryParams.orderId" placeholder="请输入工单编号" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item label="工单类型：" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择工单类型" style="width: 240px" clearable>
                <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="采编状态：" prop="markFlag">
              <el-select v-model="queryParams.markFlag" placeholder="请选择采编状态" style="width: 240px" clearable>
                <el-option v-for="item in markFlagOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="故障类别：" prop="exitFlag">
              <el-select v-model="queryParams.exitFlag" placeholder="请选择故障类别" style="width: 240px" clearable>
                <el-option v-for="item in faultCategoryOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="清除状态：" prop="clearFlag">
              <el-select v-model="queryParams.clearFlag" placeholder="请选择清除状态" style="width: 240px" clearable>
                <el-option v-for="item in faultEliminateFlagOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="工单超时状态：" prop="orderTimeoutFlag">
              <el-select v-model="queryParams.orderTimeoutFlag" placeholder="请选择超时状态" style="width: 240px" clearable>
                <el-option v-for="item in timeoutFlagOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="故障超时状态：" prop="alarmTimeoutFlag">
              <el-select v-model="queryParams.alarmTimeoutFlag" placeholder="请选择超时状态" style="width: 240px" clearable>
                <el-option v-for="item in timeoutFlagOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间：" prop="createTime">
              <el-date-picker v-model="queryParams.createStartEnd" type="daterange" start-placeholder="开始时间"
                end-placeholder="结束时间" :size="size" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="listEomsOrderTable">查询</el-button>
              <el-button @click="unsetQueryForm"><el-icon>
                  <RefreshRight />
                </el-icon>重置</el-button>
              <el-button type="primary" icon="Upload" @click="importData">导入</el-button>
              <el-button type="primary" icon="Download" @click="exportData">导出</el-button>
              <el-button type="primary" icon="Download" @click="notAvailableExportData">不可用清单导出</el-button>
            </el-form-item>

          </el-form>
          <el-table :data="eomsOrderData" style="width: 100%" @sort-change="sortChange" row-key="orderId"
            v-loading="eomsOrderLoading">
            <el-table-column fixed prop="orderId" label="工单号" width="200" align="center" />
            <el-table-column fixed prop="type" label="工单类型" width="150" align="center" :formatter="typeFormatter" />
            <el-table-column prop="county" label="归属区县" width="120" align="center" />
            <el-table-column prop="stationId" label="站号" width="120" align="center" />
            <el-table-column prop="neName" label="小区名称" width="200" align="center" />
            <el-table-column prop="alarmTopic" label="告警主题" width="200" align="center" />
            <el-table-column prop="markFlag" label="是否采编" width="150" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.markFlag != null" :type="scope.row.markFlag === 1 ? '' : 'success'"
                  disable-transitions>{{ scope.row.markFlag ==
                    1 ? "是" : "否" }}</el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="orderCreateTime" label="工单生成时间" :formatter="dateFormatter" width="200" align="center"
              sortable=" " />
            <el-table-column prop="occurTime" label="故障发生时间" width="200" :formatter="dateFormatter" align="center" />
            <el-table-column prop="clearFlag" label="故障清除状态" width="200" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.clearFlag != null" :type="scope.row.clearFlag == 0 ? 'danger' : 'success'"
                  disable-transitions>{{
                    scope.row.clearFlag
                      == 0 ? "未清除" : "已清除" }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="faultEliminateTime" label="故障清除时间" :formatter="dateFormatter" width="200"
              align="center" />
            <el-table-column prop="exitFlag" label="故障类别" width="180" align="center">
              <template #default="scope">{{ scope.row.exitFlag == 0 ? "非退服" : "退服" }}</template>
            </el-table-column>
            <el-table-column prop="orderTimeoutFlag" label="工单超时" fixed="right" width="120" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.orderTimeoutFlag == 1 ? 'danger' : 'success'" disable-transitions>
                  {{ scope.row.orderTimeoutFlag == 1 ? '超时' : '未超时' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="alarmTimeoutFlag" label="故障超时" fixed="right" width="120" align="center">
              <template #default="scope">
                <el-tag v-if="!(scope.row.orderType && scope.row.orderType == 'append')"
                  :type="scope.row.alarmTimeoutFlag == 1 ? 'danger' : 'success'" disable-transitions>
                  {{ scope.row.alarmTimeoutFlag == 1 ? '超时' : '未超时' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="工单处理剩余时间" width="160" align="center" fixed="right" sortable="custom"
              prop="orderTimeout1">
              <template #default="scope">
                <el-tag v-if="scope.row.clearFlag == 0" :type="orderTimeout > 0 ? '' : 'danger'" disable-transitions>
                  {{ timeoutFormatter(scope.row.orderTimeout) }}
                </el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="故障处理剩余时间" width="160" align="center" fixed="right" sortable="custom"
              prop="alarmTimeout1">
              <template #default="scope">
                <el-tag v-if="scope.row.clearFlag == 0" :type="alarmTimeout > 0 ? '' : 'danger'" disable-transitions>
                  {{ timeoutFormatter(scope.row.alarmTimeout) }}
                </el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center">
              <template #default="scope">
                <el-button v-if="!(scope.row.type && scope.row.type == 'sub')" link type="primary" size="small"
                  @click="showDetailDialog(scope.row.orderId)">详情</el-button>
              </template>
            </el-table-column>
            <template #empty>
              <el-empty :image-size="80" />
            </template>
          </el-table>
          <!-- <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[10, 50, 100, 200]" :small="small" :disabled="disabled" :background="background"
            layout="total, sizes, prev, pager, next" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" /> -->
          <pagination v-show="total > 0" :total="total" v-model:page="currentPage" v-model:limit="pageSize"
            @pagination="handleCurrentChange" :autoScroll="false" />
        </el-card>
      </el-col>
    </el-row>
    <el-dialog v-model="detailDialogTableVisible" title="详情信息" width="1200" @closed="closeDetailDialog">
      <el-form :model="detailForm" :inline="true" label-width="120px">
        <el-form-item label="工单标题" prop="faultTitle">
          <el-input v-model="detailForm.faultTitle" clearable style="width: 900px" disabled type="textarea" />
        </el-form-item>
        <el-form-item label="工单号" prop="orderId">
          <el-input v-model="detailForm.orderId" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="区县" prop="county">
          <el-input v-model="detailForm.county" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="站号" prop="stationId">
          <el-input v-model="detailForm.stationId" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="小区名称" prop="neName">
          <el-input v-model="detailForm.neName" clearable style="width: 550px" disabled />
        </el-form-item>
        <el-form-item label="告警主题" prop="alarmTopic">
          <el-input v-model="detailForm.alarmTopic" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="工单类别" prop="orderType">
          <!-- <el-input v-model="detailForm.orderType" clearable style="width: 200px" disabled /> -->
          <el-select v-model="detailForm.orderType" placeholder="请选择工单类别" style="width: 200px"
            :disabled="editFlag ? false : true" clearable>
            <el-option v-for="item in orderTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="工单生成时间" prop="orderCreateTime">
          <el-input v-model="detailForm.orderCreateTime" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="故障发生时间" prop="occurTime">
          <el-input v-model="detailForm.occurTime" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="故障清除时间" prop="faultEliminateTime">
          <el-input v-model="detailForm.faultEliminateTime" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="采编状态" prop="markFlag">
          <el-input v-model="detailForm.markFlag" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="故障清除状态" prop="clearFlag">
          <el-input v-model="detailForm.clearFlag" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="工单超时状态" prop="orderTimeoutFlag">
          <el-input v-model="detailForm.orderTimeoutFlag" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="故障超时状态" prop="alarmTimeoutFlag">
          <el-input v-model="detailForm.alarmTimeoutFlag" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="处理耗时" prop="handleTime">
          <el-input v-model="detailForm.handleTime" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item v-if="detailForm.orderTimeoutFlag == '已超时'" label="工单剩余时间" prop="orderTimeout">
          <el-input v-model="detailForm.orderTimeout" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item v-if="detailForm.alarmTimeoutFlag == '已超时'" label="故障剩余时间" prop="alarmTimeout">
          <el-input v-model="detailForm.alarmTimeout" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="detailForm.deviceName" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="当前环节" prop="currentNode">
          <el-input v-model="detailForm.currentNode" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="工单状态" prop="orderStatus">
          <el-input v-model="detailForm.orderStatus" clearable style="width: 200px" disabled />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="detailForm.remark" type="textarea" style="width: 900px"
            :disabled="editFlag ? false : true" />
        </el-form-item>
        <el-form-item label=" ">
          <el-button type="primary" icon="Edit" @click="editDetail" v-if="!editFlag">修改</el-button>
          <el-button type="primary" icon="Check" @click="saveDetail" v-if="editFlag">保存</el-button>
          <el-button icon="CircleClose" @click="cancelEditDetail">取消</el-button>
        </el-form-item>
      </el-form>
      <!-- 合并工单展示 -->
      <div v-if="detailForm.children && detailForm.children.length > 0" style="margin-top: 20px;">
        <el-divider>合并工单</el-divider>
        <el-table :data="appendEomsOrderData" style="width: 100%">
          <el-table-column prop="orderId" label="工单ID" width="150" align="center" />
          <el-table-column prop="neName" label="小区名称" width="200" align="center" />
          <el-table-column prop="alarmTopic" label="告警主题" width="150" align="center" />
          <el-table-column prop="exitFlag" label="故障类别" width="180" align="center">
            <template #default="scope">{{ scope.row.exitFlag == 0 ? "非退服" : "退服" }}</template>
          </el-table-column>
          <el-table-column prop="orderCreateTime" label="工单生成时间" :formatter="dateFormatter" width="160" align="center"
            sortable="custom" />
          <el-table-column prop="occurTime" label="故障发生时间" :formatter="dateFormatter" width="160" align="center" />
          <el-table-column prop="faultEliminateTime" label="故障清除时间" :formatter="dateFormatter" width="160"
            align="center" />
          <el-table-column prop="alarmLocat" label="告警定位" min-width="160" show-overflow-tooltip align="center" />
        </el-table>
      </div>
      <!-- 关联告警展示 -->
      <div v-if="detailForm.markFlag == '是'" style="margin-top: 20px;">
        <el-divider>采编关联告警</el-divider>
        <el-table :data="relatedAlarmData" style="width: 100%">
          <el-table-column prop="alarmId" label="告警ID" width="200" align="center" />
          <el-table-column prop="alarmType" label="告警类型" width="80" align="center" />
          <el-table-column prop="alarmTitle" label="告警标题" width="200" align="center" />
          <el-table-column prop="eventTime" label="发生时间" width="180" :formatter="dateFormatter" align="center" />
          <el-table-column prop="neName" label="小区名称" width="200" align="center" />
          <el-table-column prop="standardId" label="标准号" width="120" align="center" />
          <el-table-column prop="recoveryTime" label="恢复时间" :formatter="dateFormatter" align="center" />
        </el-table>
      </div>
    </el-dialog>

    <el-dialog v-model="dialogFormVisible" v-loading="loading" title="导入数据" width="1000" ref="mv" @opened="openDialog">
      <el-tabs v-model="activeName">
        <el-tab-pane label="导入数据" name="first">
          <el-form :model="form" label-width="150px" label-position="left">
            <!-- <el-form-item label="工单数据">
              <el-button type="primary" icon="开始导入" @click="doImportEomsOrder">导入</el-button>
            </el-form-item>
            <el-form-item label="告警数据">
              <el-button type="primary" icon="开始导入" @click="doImportAlarm">导入</el-button>
            </el-form-item>
            <el-form-item label="工单计算">
              <el-button type="primary" icon="开始" @click="doCalculateOrderResult">任务开始</el-button>
            </el-form-item> -->
            <el-form-item label="网络规模数据">
              <el-upload class="upload-demo" :action="uploadNetworkScaleUrl" :on-success="uploadNetworkScaleSuccess"
                :show-file-list="false" :headers="headers">
                <el-button type="primary">导入</el-button>
              </el-upload>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="导入情况" name="second">
          <el-table :data="taskData" style="width: 100%">
            <el-table-column prop="id" label="id" width="120" align="center" />
            <el-table-column prop="taskType" label="任务类型" width="120" align="center" />
            <el-table-column prop="taskStatus" label="任务状态" width="100" align="center" />
            <el-table-column prop="startDate" label="开始时间" width="120" align="center" />
            <el-table-column prop="endDate" label="结束时间" width="120" align="center" />
            <el-table-column prop="result" label="结果" align="center" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>

  <export-dialog ref="refExportDialog" @directExport="directExportData" />
</template>


<script setup>
import { ref } from 'vue';
import { queryEomsOrderstatisticsInfo, queryEomsOrderList, queryEomsOrderMaintenanceData, importAlarm, importEomsOrder, calculateOrderResult, queryImportTaskList, exportTaskList, queryEomsOrder, updateEomsOrder, queryRelatedAlarm } from '@/api/biz/maintenance';
import { ElDropdownItem, ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/auth'

import { useConfigStore } from "@/store/modules/config.js";

/* import mittBus from "@/utils/mittBus"; // mitt - 组件传参工具
mittBus.emit("setWaterMarker", 130); */

const { proxy } = getCurrentInstance();

const refExportDialog = ref(null)

const configStoreData = useConfigStore();
let securityFlagConfig = configStoreData.configList.filter(
  (item) => item.configKey === "sys.securityFlag"
)[0];
// console.log("securityFlagConfig", securityFlagConfig);

let orderMaintenanceLoading = ref(false);

const markFlagOptions = [
  {
    value: "1",
    label: '采编',
  },
  {
    value: "0",
    label: '非采编',
  },
]

const faultCategoryOptions = [
  {
    value: "1",
    label: '退服',
  },
  {
    value: "0",
    label: '非退服',
  }
]

const faultEliminateFlagOptions = [
  {
    value: "1",
    label: '已清除',
  },
  {
    value: "0",
    label: '未清除',
  }
]

const countyOptions = [
  {
    value: "海曙区",
    label: '海曙区',
  },
  {
    value: "鄞州区",
    label: '鄞州区',
  },
  {
    value: "江北区",
    label: '江北区',
  },
  {
    value: "镇海区",
    label: '镇海区',
  },
  {
    value: "北仑区",
    label: '北仑区',
  },
  {
    value: "奉化区",
    label: '奉化区',
  },
  {
    value: "慈溪市",
    label: '慈溪市',
  },
  {
    value: "余姚市",
    label: '余姚市',
  },
  {
    value: "宁海县",
    label: '宁海县',
  },
  {
    value: "象山县",
    label: '象山县',
  }
]

const timeoutFlagOptions = [
  {
    value: "1",
    label: '超时',
  },
  {
    value: "0",
    label: '未超时',
  }
]

const typeOptions = [
  {
    value: "main",
    label: '主工单',
  },
  {
    value: "sub",
    label: '子工单',
  }
]



const queryParams = ref(
  {
    county: undefined,
    markFlag: undefined,
    exitFlag: undefined,
    clearFlag: undefined,
    createStartEnd: undefined
  }
);
const eomsOrderData = ref([])
const orderstatisticsData = ref([])
const orderMaintenanceData = ref([])
const pageSize = ref(10)
const currentPage = ref(1)
const total = ref(0)

let orderstatisticsLoading = ref(false);
let eomsOrderLoading = ref(false);


const dialogFormVisible = ref(false)
const activeName = ref("first")
const form = ref({})

const eomsOrderUploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/maintenance/importEomsOrder");
const alarmUploadUrl = ref(import.meta.env.VITE_APP_BASE_API + "/maintenance/importAlarm");
const dialogPanel = ref()
const mv = ref()
const taskData = ref([])
const nowOrder = ref();
const nowSortContent = ref();

const detailDialogTableVisible = ref(false);
const detailForm = ref({})
const editFlag = ref(false)
const currentOrderId = ref()

const orderTypeOptions = [
  {
    value: "动力",
    label: '动力',
  },
  {
    value: "传输",
    label: '传输',
  },
  {
    value: "工程",
    label: '工程',
  },
  {
    value: "设备天馈GPS类",
    label: '设备天馈GPS类',
  },
  {
    value: "锁闭类",
    label: '锁闭类',
  }
]

const relatedAlarmData = ref([])
const appendEomsOrderData = ref([])
const uploadNetworkScaleUrl = ref(import.meta.env.VITE_APP_BASE_API + "/maintenance/importNetworkScale");
const headers = ref({ Authorization: "Bearer " + getToken() });

const testApi = () => {
  console.log("testApi")
  // getEomsOrderstatisticsInfo()

  getEomsOrderMaintenanceData()
  // listEomsOrderTable()
}

function getEomsOrderstatisticsInfo() {
  orderstatisticsLoading.value = true;
  queryEomsOrderstatisticsInfo().then(response => {
    orderstatisticsLoading.value = false;
    orderstatisticsData.value = response.data;
  });
}

function calculateAverage(numbers) {
  if (numbers.length === 0) return 0; // 防止除以0
  const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue);
  const average = sum / numbers.length;
  return average.toFixed(4);
}

function getEomsOrderMaintenanceData() {
  orderMaintenanceLoading.value = true;

  queryEomsOrderMaintenanceData().then(response => {
    orderMaintenanceData.value = response.data;

    // 求合计
    let tempArr = []
    orderMaintenanceData.value.forEach(item => {
      tempArr.push(item.orderQuality)
    });
    orderMaintenanceData.value[orderMaintenanceData.value.length - 1].orderQuality = calculateAverage(tempArr)

    orderMaintenanceLoading.value = false;
  });
}

/* function getEomsOrderList() {
  const param = {}
  param.pageSize = pageSize.value
  param.pageNum = currentPage.value
  eomsOrderLoading.value = true;
  queryEomsOrderList(param).then(response => {
    eomsOrderLoading.value = false;
    eomsOrderData.value = response.rows;
    total.value = response.total;
  });
} */

function dateFormatter(row, column, cellValue, index) {
  if (!cellValue) { return }
  // 创建一个新的 Date 对象
  var originalDate = new Date(cellValue);

  // 获取年、月、日、时、分、秒
  var year = originalDate.getFullYear();
  var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
  var day = ("0" + originalDate.getDate()).slice(-2);
  var hours = ("0" + originalDate.getHours()).slice(-2);
  var minutes = ("0" + originalDate.getMinutes()).slice(-2);
  var seconds = ("0" + originalDate.getSeconds()).slice(-2);

  // 格式化输出
  var formattedDateTimeString = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  return formattedDateTimeString;
}

function typeFormatter(row, column, cellValue, index) {
  if (!cellValue) { return }
  if (cellValue == 'main') {
    return '主工单';
  } else if (cellValue == 'sub') {
    return '子工单';
  }
}

function listEomsOrderTable() {
  const param = {}
  param.county = queryParams.value.county
  param.markFlag = queryParams.value.markFlag
  param.exitFlag = queryParams.value.exitFlag
  param.clearFlag = queryParams.value.clearFlag
  param.orderId = queryParams.value.orderId
  //创建时间
  if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
    param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
    param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
  }
  param.pageSize = pageSize.value
  param.pageNum = currentPage.value
  param.sortContent = nowSortContent.value;
  param.order = nowOrder.value;
  param.neName = queryParams.value.neName
  param.orderTimeoutFlag = queryParams.value.orderTimeoutFlag
  param.alarmTimeoutFlag = queryParams.value.alarmTimeoutFlag
  param.type = queryParams.value.type
  eomsOrderLoading.value = true;
  queryEomsOrderList(param).then(response => {
    eomsOrderLoading.value = false;
    eomsOrderData.value = response.rows;
    total.value = response.total;
  });
}

function eomsOrderUploadSuccess(response, uploadFile, uploadFiles) {
  dialogPanel.value.close()
  var msg = ''
  if (response.data) {
    if (response.data.successFlag) {
      msg = "导入完成！总数据为" + response.data.totalNum + ",成功导入条数：" + response.data.successNum + ",失败导入条数：" + response.data.errorNum
    } else {
      msg = "导入失败！错误信息：" + response.data.errorMsg
    }
  }

  ElMessageBox.alert(msg, '导入情况', {
    confirmButtonText: 'OK',
  })
}

function eomsOrderUploadProgress(evt, uploadFile, uploadFiles) {
  dialogPanel.value = ElLoading.service({
    target: mv.value.dialogRef, // el-dialog 对象
    text: '导入中...', // Loading 的提示信息
    background: 'rgba(0,0,0,0.7)', // 设置背景颜色和透明度
  })
}

function handleSizeChange() {
  listEomsOrderTable()
}

function handleCurrentChange() {
  listEomsOrderTable()
}

//导入数据
function importData() {
  dialogFormVisible.value = true
}

function doImportEomsOrder() {
  importEomsOrder().then(response => {
    let msg = "";
    if (response.data.successFlag) {
      msg = "开始导入：任务号为" + response.data.taskNo;
    } else {
      msg = "导入失败:" + response.data.errorMsg;
    }
    ElMessageBox.alert(msg, '导入情况', {
      confirmButtonText: 'OK',
    })
  })
}

function doImportAlarm() {
  importAlarm().then(response => {
    let msg = "";
    if (response.data.successFlag) {
      msg = "开始导入：任务号为" + response.data.taskNo;
    } else {
      msg = "导入失败:" + response.data.errorMsg;
    }
    ElMessageBox.alert(msg, '导入情况', {
      confirmButtonText: 'OK',
    })
  })
}

function doCalculateOrderResult() {
  calculateOrderResult().then(response => {
    let msg = "任务开始！任务号为：" + response.data;
    ElMessageBox.alert(msg, '导入情况', {
      confirmButtonText: 'OK',
    })
  })
}

function openDialog() {
  //查询最新的任务状态
  queryImportTaskList().then(response => {
    taskData.value = response.data;
  })

}

function exportData() {
  const param = {}
  param.county = queryParams.value.county
  param.markFlag = queryParams.value.markFlag
  param.exitFlag = queryParams.value.exitFlag
  param.clearFlag = queryParams.value.clearFlag
  //创建时间
  if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
    param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
    param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
  }
  /* proxy.download("/maintenance/exportTaskList", {
    ...param
  }, `eoms_order_${new Date().getTime()}.xlsx`); */

  if (securityFlagConfig.configValue == "true") {
    //开启金库模式
    refExportDialog.value.show(param);
  } else {
    proxy.download("/maintenance/exportTaskList", {
      ...param
    }, `无线维护工单_${new Date().getTime()}.xlsx`);
  }
}

// 不可用清单导出
const notAvailableExportData = () => {
  proxy.download("/maintenance/exportUnavailtimeList", {
  }, `不可用清单_${new Date().getTime()}.xlsx`);
}

// 工单维护指标
const orderMaintenanceExportData = () => {
  console.log("工单维护指标")

  /* const param = {}
  param.county = queryParams.value.county
  param.markFlag = queryParams.value.markFlag
  param.exitFlag = queryParams.value.exitFlag
  param.clearFlag = queryParams.value.clearFlag

  proxy.download("/maintenance/exportTaskList", {
    ...param
  }, `工单维护指标_${new Date().getTime()}.xlsx`); */

  const param = {}

  proxy.download("/maintenance/exportOrderMaintenance", {
    ...param
  }, `工单维护指标_${new Date().getTime()}.xlsx`);
}

function directExportData() {
  const param = {}
  param.county = queryParams.value.county
  param.markFlag = queryParams.value.markFlag
  param.exitFlag = queryParams.value.exitFlag
  param.clearFlag = queryParams.value.clearFlag
  //创建时间
  if (queryParams.value.createStartEnd && queryParams.value.createStartEnd.length > 0) {
    param.createStart = queryParams.value.createStartEnd[0].toLocaleDateString()
    param.createEnd = queryParams.value.createStartEnd[1].toLocaleDateString()
  }
  proxy.download("/maintenance/exportTaskDirectList", {
    ...param
  }, `无线维护工单(剔除敏感数据)_${new Date().getTime()}.xlsx`);
}

function remainderFormatter(exitFlag, handleTime) {
  if (exitFlag == 0 && handleTime < 24) {
    return convertHoursToHoursMinutes((24 - handleTime).toFixed(2));
  } else if (exitFlag == 1 && handleTime < 8) {
    return convertHoursToHoursMinutes((8 - handleTime).toFixed(2));
  } else if (exitFlag == 0 && handleTime >= 24) {
    return "超时" + convertHoursToHoursMinutes((handleTime - 24).toFixed(2));
  } else if (exitFlag == 1 && handleTime >= 8) {
    return "超时" + convertHoursToHoursMinutes((handleTime - 8).toFixed(2));
  } else {
    return 0
  }
}

function timeoutFormatter(time) {
  if (time) {
    if (time >= 0) {
      return convertHoursToHoursMinutes(time.toFixed(2));
    } else if (time < 0) {
      return "超时" + convertHoursToHoursMinutes(Math.abs(time.toFixed(2)));
    } else {
      return 0
    }
  }
  return 0
}

function convertHoursToHoursMinutes(hoursFloat) {
  // 取出整数部分作为小时数  
  var hours = Math.floor(hoursFloat);

  // 取出小数部分并转换为分钟（乘以60）  
  var minutes = Math.round((hoursFloat - hours) * 60);

  // 如果分钟数小于10，前面补0  
  if (minutes < 10) {
    minutes = '0' + minutes;
  }

  // 返回格式化的字符串  
  return hours + 'h' + minutes + 'min';
}

function initCreateTime() {
  var today = new Date();
  var currentMonth = today.getMonth();
  var currentYear = today.getFullYear();

  var firstDayOfMonth, lastDayOfMonth;

  // 判断今天是否在5号之前
  if (today.getDate() <= 5) {
    // 如果在5号之前，返回上个月的第一天和最后一天
    if (currentMonth === 0) {
      // 如果当前月份是1月，则返回上一年的12月份
      firstDayOfMonth = new Date(currentYear - 1, 11, 1);
      lastDayOfMonth = new Date(currentYear - 1, 12, 1);
    } else {
      firstDayOfMonth = new Date(currentYear, currentMonth - 1, 1);
      lastDayOfMonth = new Date(currentYear, currentMonth, 1);
    }
  } else {
    // 如果在5号之后，返回这个月的第一天和最后一天
    firstDayOfMonth = new Date(currentYear, currentMonth, 1);
    lastDayOfMonth = new Date(currentYear, currentMonth + 1, 1);
  }
  queryParams.value.createStartEnd = [firstDayOfMonth, lastDayOfMonth]
}

// 剩余时间排序
function sortChange(column, prop, order) {
  nowOrder.value = column.order;
  if (column.prop == 'orderTimeout1') {
    nowSortContent.value = 'orderTimeout'
  } else if (column.prop == 'alarmTimeout1') {
    nowSortContent.value = 'alarmTimeout'
  } else {
    nowSortContent.value = column.prop;
  }
  listEomsOrderTable();
}

function showDetailDialog(orderId) {
  let param = { orderId: orderId }
  queryEomsOrder(param).then(res => {
    detailForm.value = res.data;
    //时间格式转换
    detailForm.value.orderCreateTime = dateFormatter(null, null, detailForm.value.orderCreateTime, null)
    detailForm.value.occurTime = dateFormatter(null, null, detailForm.value.occurTime, null)
    detailForm.value.faultEliminateTime = dateFormatter(null, null, detailForm.value.faultEliminateTime, null)
    //类型转换
    detailForm.value.markFlag = detailForm.value.markFlag == 0 ? '否' : '是'
    detailForm.value.clearFlag = detailForm.value.clearFlag == 0 ? '未清除' : '已清除'

    detailForm.value.orderTimeoutFlag = detailForm.value.orderTimeoutFlag == 0 ? '未超时' : '已超时'
    detailForm.value.alarmTimeoutFlag = detailForm.value.alarmTimeoutFlag == 0 ? '未超时' : '已超时'

    detailForm.value.handleTime = timeoutFormatter(detailForm.value.handleTime)
    detailForm.value.orderTimeout = timeoutFormatter(detailForm.value.orderTimeout)
    detailForm.value.alarmTimeout = timeoutFormatter(detailForm.value.alarmTimeout)

    currentOrderId.value = orderId
    appendEomsOrderData.value = detailForm.value.children

    queryRelatedAlarm(param).then(res => {
      relatedAlarmData.value = res.data
    })

    detailDialogTableVisible.value = true
  })
}

function editDetail() {
  editFlag.value = true
}

function cancelEditDetail() {
  editFlag.value = false
  showDetailDialog(currentOrderId.value)
}

function saveDetail() {
  let param = {}
  param.orderId = detailForm.value.orderId
  param.orderType = detailForm.value.orderType
  param.remark = detailForm.value.remark
  updateEomsOrder(param).then(res => {
    ElMessage.success('操作成功！')
    showDetailDialog(currentOrderId.value)
  })

}

function downloadLongTimeOrder() {
  proxy.download("/maintenance/exportLongTimeOrder", {}, `超时工单_${new Date().getTime()}.xlsx`);
}

function uploadNetworkScaleSuccess(res, file, fileList) {
  dialogFormVisible.value = false
  ElMessage.success(res.msg)
}

function unsetQueryForm() {

  queryParams.value = {
    county: null,
    neName: null,
    orderId: null,
    type: null,
    markFlag: null,
    exitFlag: null,
    clearFlag: null,
    orderTimeoutFlag: null,
    alarmTimeoutFlag: null,
  }
  initCreateTime()

}

getEomsOrderstatisticsInfo()
getEomsOrderMaintenanceData()
initCreateTime()
listEomsOrderTable()

</script>